package com.zzw.schedule;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Administrator
 */
public class DefaultAsyncRTask {

    private static final Logger logger = LoggerFactory.getLogger(DefaultAsyncRTask.class);

    private final RedissonClient redissonClient;


    public DefaultAsyncRTask(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    public void process(RTask rTask) {
        RLock lock = null;
        try {
            lock = redissonClient.getLock(rTask.key());
            boolean tryLock = lock.tryLock();
            if (tryLock) {
                logger.info("task {} get lock,start execute task", rTask.key());
                rTask.task();
            } else {
                logger.info("task {} lose lock,task is executing...", rTask.key());
            }
        } catch (Exception e) {
            logger.error("R task get lock error", e);
        } finally {
            if (lock != null && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    public interface RTask {

        String key();

        void task();
    }

}
